﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Data;
using System.Windows.Media;

namespace Dotway.WPF.Controls.Converters
{
    public class RgbToColorMultiConverter : IMultiValueConverter
    {
        #region IMultiValueConverter Members

        /// <summary>
        /// Convert a multibinding to a color. Use the parameter to specify static values. 
        /// The parameter can be used as ConverterParameter="A R G B" where the order indicates
        /// the order of the bindings. Set a static value ConverterParameter="255 R G 15" for a
        /// color with alpha=255 and blue=15.
        /// </summary>
        /// <param name="values"></param>
        /// <param name="targetType"></param>
        /// <param name="parameter"></param>
        /// <param name="culture"></param>
        /// <returns></returns>
        public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            byte[] argb = new byte[] { 0, 0, 0, 0 };

            string colorParameter = (string)parameter;
            string[] parameterInfo = colorParameter.Split(new char[]{' '});

            int bindingIndex = 0;
            int parameterIndex = 0;
            foreach (string s in parameterInfo)
            {
                if (!byte.TryParse(s, out argb[parameterIndex]))
                {
                    if (s == "A")
                    {
                        argb[0] = (byte)values[bindingIndex];
                        bindingIndex++;
                    }
                    else if (s == "R")
                    {
                        argb[1] = (byte)values[bindingIndex];
                        bindingIndex++;
                    }
                    else if (s == "G")
                    {
                        argb[2] = (byte)values[bindingIndex];
                        bindingIndex++;
                    }
                    else if (s == "B")
                    {
                        argb[3] = (byte)values[bindingIndex];
                        bindingIndex++;
                    }
                }
                parameterIndex++;
            }

            return Color.FromArgb(argb[0], argb[1], argb[2], argb[3]);
        }

        public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }

        #endregion
    }
}
